package com.huang.web.controller;

import com.github.pagehelper.PageInfo;
import com.huang.domain.PageBean;
import com.huang.domain.Work;
import com.huang.service.WorkService;
import com.huang.utils.FileNameUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@RequestMapping("/work")
public class WorkController {
    @Autowired
    private WorkService workService;

    @RequestMapping("/list")
    public ModelAndView list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "12") Integer pageSize) {
        // 查询
        PageInfo<Work> pageInfo = workService.findByPage(pageNum, pageSize);
        // 返回
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/works/work-list");
        mv.addObject("pageInfo", pageInfo);
        return mv;
    }

    @RequestMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file, @RequestParam("text") String text, HttpServletRequest request) throws IOException {

        System.out.println("上传开始！");
        // 获取文件名
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String randomFileName = FileNameUtil.getRandomFileName();
        System.out.println("randomFileName = " + randomFileName+suffix);

        String path = request.getSession().getServletContext().getRealPath("/img/") + randomFileName+suffix;
        System.out.println("path = " + path);
        file.transferTo(new File(path));

        Work work = new Work();
        work.setFilename(randomFileName+suffix);
        work.setDescription(text);
        //work.setPath(path);
        workService.add(work);
        return "redirect:/work/list.do";
    }


}
